package com.jmcgg.freesky.common.db;

import java.sql.SQLException;

import org.apache.log4j.Logger;


/**
 * @author <b>Jacky Chou</b> (Copyright &#169; 2005~2010 AFSS [Amei's FreeSky
 *         Studio])
 * @version 1.2.0, 2008-02-23, Upgrade freesky.jar to 1.2.0 with Struts 2 <br>
 *          1.0.0, 2006-05-30, Initial Version
 */
public class InsertHelper extends TableHelper {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(InsertHelper.class);

	public InsertHelper() {
		this.opType = DBType.OP_INSERT;
	}

	public InsertHelper(DBConnBean conn) {
		super(conn);
		this.opType = DBType.OP_INSERT;
	}

	public InsertHelper(DBConnBean conn, String tableName) {
		super(conn, tableName);
		this.opType = DBType.OP_INSERT;
	}

	public InsertHelper(DBConnBean conn, String tableName, String opType) {
		super(conn, tableName, opType);
	}

	public String getSQL() {
		if (this.fvList == null || this.fvList.size() == 0)
			return null;
		String pre = "INSERT INTO " + this.tableName;
		String fields = "(";
		String values = " VALUES(";
		for (int i = 0; i < this.fvList.size(); i++) {
			FieldValueBean bean = (FieldValueBean) fvList.get(i);
			if (bean.getValue() != null) {
				if (i > 0) {
					fields += ",";
					values += ",";
				}
				if (bean.getType().equals(DBType.F_STRING)) {
					fields += bean.getField();
					values += "'" + bean.getValue() + "'";
				} else if (bean.getType().equals(DBType.F_INTEGER)) {
					fields += bean.getField();
					values += bean.getValue();
				} else if (bean.getType().equals(DBType.F_DOUBLE)) {
					fields += bean.getField();
					values += bean.getValue();
				}
			}
		}
		fields += ") ";
		values += ")";

		String sql = pre + fields + values;
		if (logger.isDebugEnabled()) {
			logger.debug("getSQL() - String sql=" + sql);
		}

		return sql;
	}

	public int execute() {
		if (conn == null)
			return 0;
		try {
			String sql = getSQL();
			return conn.executeUpdate(sql);
		} catch (SQLException e) {
			logger.error(
					"execute() - Error occured when execute SQL statement:", e);
		}
		return 0;
	}
}
